//
//  YDRefreshController.swift
//  weibo
//
//  Created by 孙亚东 on 16/7/1.
//  Copyright © 2016年 Sunyadong. All rights reserved.
//

import UIKit

enum refreshControllerType: Int {

    case Normal = 0
    case Pulling = 1
    case Loading = 2

}

class YDRefreshController: UIControl {
    
    
    //定义一个l类型
    var type: refreshControllerType = .Normal {
    
    
        didSet {
        
            switch (type) {
            
            case .Normal:
                
                self.messageLab.text = "下拉刷新"
                
                self.arrowImage.hidden = false
                
                self.loadingImage.stopAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowImage.transform = CGAffineTransformIdentity
                    
                })
                
            case .Pulling:
                
                self.messageLab.text = "开始刷新"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
                
            case .Loading:
                
                
                self.messageLab.text = "加载中"
                
                self.arrowImage.hidden = true
                
                self.loadingImage.startAnimating()
                
                //让视图停留一下
                
                var inset = scrollView!.contentInset
                
                inset.top = inset.top + self.bounds.height
                
                scrollView?.contentInset = inset

                sendActionsForControlEvents(.ValueChanged)
            
            
            }

        }
  
    }
    

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        
        setupUI()
        
        
    }
      
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
        
    }
    
    //声明一个scorllView接收父控件
    
    var scrollView: UIScrollView?
    
    // 重写一个新的方法，利用当父控件添加self时，调用
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        //判断一下，如果添加到scrollView上时，添加kvo监听
        if newSuperview is UIScrollView {
            
            //将newSuperView 进行强转
            scrollView = newSuperview as? UIScrollView
            
            newSuperview?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        
      
        }

        
    }
   //实现监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
 
        
        if scrollView!.dragging == true {
        
        
            if object!.contentOffset.y < -135.0 && type == .Normal {
                
                type = .Pulling
                
                
            }else if object!.contentOffset.y > -135.0 && type == .Pulling {
                
                
                type = .Normal
                
                
            }

        } else {
        
            //判断如果当前的offset< -135,改变text
            if object!.contentOffset.y < -135.0 && type == .Pulling {
            

                type = .Loading
        
            }
 
        }
        
        
    }
    
    
    //给用户添加一个方法，让加载停止
    
    func endRefreshing() {
        
        if type == .Loading {
    
        //改变inset
        var inset = scrollView?.contentInset
    
        inset?.top = (inset?.top)! - self.bounds.height
        
        scrollView?.contentInset = inset!
            
        }
        
        type = .Normal
        

    
    }
    
 
    func  setupUI () {
        
        //设置自己的frame
        self.frame = CGRectMake(0, -44, screenWidth, 44)
        
        
        //添加子空间
        addSubview(arrowImage)
        addSubview(messageLab)
        addSubview(loadingImage)
        
        
        
        //设置子控件的frame
        arrowImage.snp_makeConstraints { (make) -> Void in
        
            make.centerX.equalTo(self.snp_centerX).offset(-40)
            make.centerY.equalTo(self)
            
            
        }
        
        
        messageLab.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(arrowImage.snp_right)
            make.centerY.equalTo(self)
            
            
        }
        
        
        loadingImage.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self.snp_centerX).offset(-40)
            make.centerY.equalTo(self)
            
        
            
        }
        
    
    
    
    
    }
    
    
    //懒加载控件
     //箭头
    
    lazy var arrowImage: UIImageView = {
    
        let arrow = UIImageView()
    
        arrow.image = UIImage(named: "tableview_pull_refresh")
        
        arrow.sizeToFit()
 
        return arrow
    
    
    }()
    
    
    //提示语
    lazy var messageLab: UILabel = {
    
        let lab = UILabel()
    
        lab.text = "下拉刷新"
        
        lab.textColor = UIColor.lightGrayColor()
    
        return lab
    
    
    }()
    
    
    //菊花
    lazy var loadingImage: UIActivityIndicatorView = {
    
    
        let loadingImage = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        
        return loadingImage
    
    
    }()
    
    

    

}
